import React, { useState, useEffect } from 'react'
import {
  Card,
  Tabs,
  Row,
  Col,
  Button,
  Space,
  Typography,
  message,
  Spin,
} from 'antd'
import {
  HistoryOutlined,
  BarChartOutlined,
  FileTextOutlined,
  SettingOutlined,
  ReloadOutlined,
} from '@ant-design/icons'
import ExecutionHistory from '@/components/Execution/ExecutionHistory'
import ExecutionStats from '@/components/Execution/ExecutionStats'
import ExecutionLogs from '@/components/Execution/ExecutionLogs'
import LogManagement from '@/components/Execution/LogManagement'
import {
  getExecutionHistory,
  getExecutionStats,
  deleteExecutionHistory,
  clearExecutionHistory,
  exportExecutionResult,
} from '@/services/executionAPI'
import type { ExecutionHistoryItem } from '@/types/execution'
import type { LogEntry } from '@/components/Execution/ExecutionLogs'

const { Title } = Typography
const { TabPane } = Tabs

const ExecutionHistoryPage: React.FC = () => {
  const [activeTab, setActiveTab] = useState('history')
  const [loading, setLoading] = useState(false)
  const [historyData, setHistoryData] = useState<ExecutionHistoryItem[]>([])
  const [logsData, setLogsData] = useState<LogEntry[]>([])
  const [connections, setConnections] = useState<Array<{ id: string; name: string }>>([])
  const [selectedConnection, setSelectedConnection] = useState<string>()
  const [autoRefresh, setAutoRefresh] = useState(false)
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 20,
    total: 0,
  })

  // 加载执行历史
  const loadExecutionHistory = async (page = 1, pageSize = 20) => {
    setLoading(true)
    try {
      const response = await getExecutionHistory({
        connection_id: selectedConnection,
        limit: pageSize,
        offset: (page - 1) * pageSize,
      })

      if (response.success) {
        setHistoryData(response.data.executions)
        setPagination(prev => ({
          ...prev,
          current: page,
          total: response.data.total,
        }))
      }
    } catch (error) {
      message.error('加载执行历史失败')
    } finally {
      setLoading(false)
    }
  }

  // 模拟加载日志数据
  const loadLogs = async () => {
    // 这里应该调用实际的日志API
    // 现在使用模拟数据
    const mockLogs: LogEntry[] = [
      {
        id: '1',
        timestamp: new Date().toISOString(),
        level: 'info',
        message: 'SQL执行开始',
        execution_id: 'exec-123',
        connection_id: 'conn-1',
        connection_name: '生产环境',
        user_name: '张三',
        sql: 'SELECT * FROM users WHERE status = "active"',
      },
      {
        id: '2',
        timestamp: new Date(Date.now() - 60000).toISOString(),
        level: 'error',
        message: 'SQL执行失败',
        execution_id: 'exec-122',
        connection_id: 'conn-1',
        connection_name: '生产环境',
        user_name: '李四',
        sql: 'SELECT * FROM invalid_table',
        error_details: 'Table "invalid_table" doesn\'t exist',
        duration: 1500,
      },
      {
        id: '3',
        timestamp: new Date(Date.now() - 120000).toISOString(),
        level: 'warn',
        message: '查询执行时间较长',
        execution_id: 'exec-121',
        connection_id: 'conn-2',
        connection_name: '测试环境',
        user_name: '王五',
        sql: 'SELECT COUNT(*) FROM large_table',
        duration: 15000,
      },
    ]
    setLogsData(mockLogs)
  }

  // 模拟加载连接列表
  const loadConnections = async () => {
    // 这里应该调用实际的连接API
    const mockConnections = [
      { id: 'conn-1', name: '生产环境' },
      { id: 'conn-2', name: '测试环境' },
      { id: 'conn-3', name: '开发环境' },
    ]
    setConnections(mockConnections)
  }

  // 初始化数据
  useEffect(() => {
    loadExecutionHistory()
    loadLogs()
    loadConnections()
  }, [selectedConnection])

  // 处理重新执行
  const handleReExecute = (sql: string, connectionId: string) => {
    // 这里应该调用执行API
    message.info('重新执行功能待实现')
  }

  // 处理删除历史记录
  const handleDeleteHistory = async (id: string) => {
    try {
      const response = await deleteExecutionHistory(id)
      if (response.success) {
        message.success('删除成功')
        loadExecutionHistory(pagination.current, pagination.pageSize)
      }
    } catch (error) {
      message.error('删除失败')
    }
  }

  // 处理清空历史记录
  const handleClearHistory = async () => {
    try {
      const response = await clearExecutionHistory()
      if (response.success) {
        message.success('清空成功')
        loadExecutionHistory(1, pagination.pageSize)
      }
    } catch (error) {
      message.error('清空失败')
    }
  }

  // 处理日志导出
  const handleExportLogs = async (config: any) => {
    // 模拟导出
    await new Promise(resolve => setTimeout(resolve, 2000))
    message.success('日志导出完成')
  }

  // 处理日志清理
  const handleCleanupLogs = async (config: any) => {
    // 模拟清理
    await new Promise(resolve => setTimeout(resolve, 3000))
    message.success('日志清理完成')
    loadLogs()
  }

  // 处理配置更新
  const handleUpdateConfig = async (config: any) => {
    // 模拟配置更新
    await new Promise(resolve => setTimeout(resolve, 1000))
    message.success('配置更新成功')
  }

  // 刷新当前标签页数据
  const handleRefresh = () => {
    switch (activeTab) {
      case 'history':
        loadExecutionHistory(pagination.current, pagination.pageSize)
        break
      case 'stats':
        // 统计组件内部会自动刷新
        break
      case 'logs':
        loadLogs()
        break
      case 'management':
        loadLogs()
        break
    }
  }

  return (
    <div style={{ padding: '24px' }}>
      <Card>
        <div style={{ 
          display: 'flex', 
          justifyContent: 'space-between', 
          alignItems: 'center',
          marginBottom: 24,
        }}>
          <Title level={2} style={{ margin: 0 }}>
            执行历史和日志管理
          </Title>
          
          <Space>
            <Button
              icon={<ReloadOutlined />}
              onClick={handleRefresh}
              loading={loading}
            >
              刷新
            </Button>
          </Space>
        </div>

        <Tabs 
          activeKey={activeTab} 
          onChange={setActiveTab}
          type="card"
        >
          <TabPane
            tab={
              <Space>
                <HistoryOutlined />
                <span>执行历史</span>
              </Space>
            }
            key="history"
          >
            <ExecutionHistory
              history={historyData}
              loading={loading}
              onExecute={handleReExecute}
              onDelete={handleDeleteHistory}
              onClear={handleClearHistory}
              onLoadMore={() => {
                const nextPage = pagination.current + 1
                loadExecutionHistory(nextPage, pagination.pageSize)
              }}
              hasMore={pagination.current * pagination.pageSize < pagination.total}
              maxHeight={600}
            />
          </TabPane>

          <TabPane
            tab={
              <Space>
                <BarChartOutlined />
                <span>性能统计</span>
              </Space>
            }
            key="stats"
          >
            <ExecutionStats
              connectionId={selectedConnection}
              onConnectionChange={setSelectedConnection}
              connections={connections}
            />
          </TabPane>

          <TabPane
            tab={
              <Space>
                <FileTextOutlined />
                <span>执行日志</span>
              </Space>
            }
            key="logs"
          >
            <ExecutionLogs
              logs={logsData}
              loading={loading}
              onRefresh={loadLogs}
              onExport={handleExportLogs}
              autoRefresh={autoRefresh}
              onAutoRefreshChange={setAutoRefresh}
              maxHeight={600}
            />
          </TabPane>

          <TabPane
            tab={
              <Space>
                <SettingOutlined />
                <span>日志管理</span>
              </Space>
            }
            key="management"
          >
            <LogManagement
              logStats={{
                totalLogs: logsData.length,
                totalSize: 1024 * 1024 * 50, // 50MB
                oldestLog: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString(),
                newestLog: new Date().toISOString(),
                logsByLevel: {
                  error: 10,
                  warn: 25,
                  info: 150,
                  debug: 300,
                },
                logsByConnection: {
                  '生产环境': 200,
                  '测试环境': 180,
                  '开发环境': 105,
                },
              }}
              onExport={handleExportLogs}
              onCleanup={handleCleanupLogs}
              onUpdateConfig={handleUpdateConfig}
              connections={connections}
            />
          </TabPane>
        </Tabs>
      </Card>
    </div>
  )
}

export default ExecutionHistoryPage